<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>固定侧边栏</title>
    <style>
      * {
        padding: 0;
        margin: 0;
        list-style: none;
      }
      a {
        text-decoration: none;
      }
      div {
        width: 1200px;
        text-align: center;
        margin: 0 auto;
      }
      .top {
        height: 200px;
        background-color: pink;
      }
      .banner {
        height: 300px;
        margin-top: 20px;
        background-color: #9bceea;
      }
      .main {
        height: 900px;
        margin-top: 20px;
        background-color: moccasin;
      }
      .footer {
        height: 400px;
        margin-top: 20px;
        background-color: aquamarine;
      }
      .help {
        position: absolute;
        top: 560px;
        left: 1360px;
        height: 100px;
        width: 50px;
        background-color: orange;
      }
      .back {
        display: none;
      }
    </style>
  </head>
  <body>
    <div class="top" id="top">top</div>
    <div class="banner">banner</div>
    <div class="main">main</div>
    <div class="footer">footer</div>
    <div class="help">
      <ul>
        <li class="back">返回顶部</li>
      </ul>
    </div>
    <script>
      var lan = document.querySelector(".help");
      var li = document.querySelector(".back");
      document.addEventListener("scroll", function () {
        console.log(document.documentElement.scrollTop);
        if (document.documentElement.scrollTop >= 560) {
          lan.style.position = "fixed";
          lan.style.top = "0px";
          if (document.documentElement.scrollTop >= 900) {
            li.style.display = "block";
          }
        } else {
          lan.style.position = "absolute";
          lan.style.top = "560px";
          li.style.display = "none";
        }
      });
      li.addEventListener("click", function () {
        //因为是window的动画
        move(window, 0);
      });
      // console.log(window.scrollY);
      var move = function (obj, target, callback) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
          var step = (target - window.scrollY) / 10;
          step = step > 0 ? Math.ceil(step) : Math.floor(step);
          if (obj.offsetLeft == target) {
            clearInterval(obj.timer);
            //if (callback) callback();
            callback && callback();
          }
          // obj.style.left = obj.offsetLeft + step + "px";
          window.scroll(0, window.scrollY + step);
        }, 15);
      };
    </script>
  </body>
</html>
